import api from './api'
import { logger } from '@/utils/logger'

// AI接口专属超时时间（90秒）
// AI模型响应需要较长时间，避免前端超时
const AI_TIMEOUT = 90000

/**
 * AI服务接口
 * 提供条文解读、法律问答、场景分析、搜索建议等AI功能
 */
export class AIService {
  
  /**
   * 条文解读
   * @param {string} articleContent - 条文内容
   * @returns {Promise<Object>} AI解读结果
   */
  async explainArticle(articleContent) {
    try {
      logger.userAction('AI条文解读', { contentLength: articleContent.length })
      const response = await api.post('/ai/explain', {
        article_content: articleContent
      }, {
        timeout: AI_TIMEOUT
      })
      
      if (response.success) {
        return {
          success: true,
          explanation: response.data.explanation,
          timestamp: response.timestamp
        }
      } else {
        throw new Error(response.error?.message || 'AI解读失败')
      }
    } catch (error) {
      logger.error('AI条文解读失败:', error)
      throw error
    }
  }

  /**
   * 法律问答
   * @param {string} question - 用户问题
   * @returns {Promise<Object>} AI回答结果
   */
  async answerQuestion(question) {
    try {
      logger.userAction('AI法律问答', { questionLength: question.length })
      const response = await api.post('/ai/question', {
        question: question
      }, {
        timeout: AI_TIMEOUT
      })
      
      if (response.success) {
        return {
          success: true,
          answer: response.data.answer,
          timestamp: response.timestamp
        }
      } else {
        throw new Error(response.error?.message || 'AI问答失败')
      }
    } catch (error) {
      logger.error('AI法律问答失败:', error)
      throw error
    }
  }

  /**
   * 获取搜索建议
   * @param {string} query - 搜索词
   * @returns {Promise<Object>} 搜索建议结果
   */
  async getSearchSuggestions(query) {
    try {
      logger.userAction('AI搜索建议', { query })
      const response = await api.get('/ai/suggestions', {
        params: { query }
      })
      
      if (response.success) {
        return {
          success: true,
          suggestions: response.data.suggestions,
          timestamp: response.timestamp
        }
      } else {
        throw new Error(response.error?.message || '获取搜索建议失败')
      }
    } catch (error) {
      logger.error('AI搜索建议失败:', error)
      throw error
    }
  }

  /**
   * 法律场景分析
   * @param {string} scenario - 场景描述
   * @returns {Promise<Object>} 场景分析结果
   */
  async analyzeScenario(scenario) {
    try {
      logger.userAction('AI场景分析', { scenarioLength: scenario.length })
      const response = await api.post('/ai/scenario', {
        scenario: scenario
      }, {
        timeout: AI_TIMEOUT
      })
      
      if (response.success) {
        return {
          success: true,
          analysis: response.data.analysis,
          feedback: response.data.feedback, // 可能为undefined
          timestamp: response.timestamp
        }
      } else {
        throw new Error(response.error?.message || 'AI场景分析失败')
      }
    } catch (error) {
      logger.error('AI场景分析失败:', error)
      throw error
    }
  }

  /**
   * 检查AI服务健康状态
   * @returns {Promise<Object>} 健康检查结果
   */
  async checkHealth() {
    try {
      const response = await api.get('/ai/health')
      
      if (response.success) {
        return {
          success: true,
          status: response.data.status,
          model: response.data.model,
          apiAvailable: response.data.api_available,
          responseTime: response.data.response_time
        }
      } else {
        throw new Error('AI服务不可用')
      }
    } catch (error) {
      logger.error('AI健康检查失败:', error)
      throw error
    }
  }
}

// 创建单例实例
export const aiService = new AIService()
export default aiService

